//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

package api_coll_dao

import (
	"context"

	"atomgit.com/openlinksaas/api-server/dao/db_ns"
	"atomgit.com/openlinksaas/proto-gen-go.git/http_custom_api"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
)

type CustomExtraInfoDbItem struct {
	ApiCollId   string `bson:"_id"`
	NetProtocol string `bson:"netProtocol"`
}

func (item *CustomExtraInfoDbItem) ToCustomExtraInfo() *http_custom_api.CustomExtraInfo {
	return &http_custom_api.CustomExtraInfo{
		ApiCollId:   item.ApiCollId,
		NetProtocol: item.NetProtocol,
	}
}

type _CustomExtraDao struct {
	mc *mongo.Collection
}

func newCustomExtraDao(db *mongo.Database) (*_CustomExtraDao, error) {
	mc := db.Collection(db_ns.DB_NS_API_COLLECTION + "custom")
	return &_CustomExtraDao{mc: mc}, nil
}

func (db *_CustomExtraDao) Insert(ctx context.Context, dbItem *CustomExtraInfoDbItem) error {
	_, err := db.mc.InsertOne(ctx, dbItem)
	return err
}

func (db *_CustomExtraDao) Update(ctx context.Context, apiCollId, netProtocol string) error {
	_, err := db.mc.UpdateOne(ctx, bson.M{"_id": apiCollId}, bson.M{"$set": bson.M{"netProtocol": netProtocol}})
	return err
}

func (db *_CustomExtraDao) Get(ctx context.Context, apiCollId string) (*CustomExtraInfoDbItem, error) {
	retItem := &CustomExtraInfoDbItem{}
	err := db.mc.FindOne(ctx, bson.M{"_id": apiCollId}).Decode(retItem)
	return retItem, err
}

func (db *_CustomExtraDao) Exist(ctx context.Context, apiCollId string) (bool, error) {
	count, err := db.mc.CountDocuments(ctx, bson.M{"_id": apiCollId})
	return count > 0, err
}

func (db *_CustomExtraDao) Remove(ctx context.Context, apiCollId string) error {
	_, err := db.mc.DeleteOne(ctx, bson.M{"_id": apiCollId})
	return err
}
